# -*- coding: utf8 -*-

from project.mysql.table import Table

class TableHash( Table ):

    _table_name = "hash"

    def create( self ):
        cur = self.getCursor()

        # Create table
        cur.execute(
            "CREATE TABLE IF NOT EXISTS %s (" % self._table_name+
            "id INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY, "+
            "value VARCHAR(255) NOT NULL ) ENGINE %s" % self.getEngine()
        )
        try:
            cur.execute(
                "ALTER TABLE `%s` ADD INDEX hash (value)" % self._table_name
            )
        except:
            pass

        cur.close()
        return


    def insert( self, value ):
        cur = self.getCursor()

        rows = cur.execute("INSERT INTO hash(value) VALUES (%s)", (value,))

        self.getConnection().commit()

        hash_id = None
        if rows:
            hash_id = self.getConnection().insert_id()

        cur.close()
        return hash_id


    def find( self, value ):
        cur = self.getCursor()
        cur.execute("SELECT * FROM hash WHERE value=%(value)s",
                {"value": value}
        )
        item = cur.fetchone()
        cur.close()
        if not item:
            item = False
        return item

    def get_by_ids( self, hash_ids ):
        cur = self.getCursor()

        hashes = []
        if len(hash_ids):
            cur.execute("SELECT * FROM hash WHERE id IN (" + ",".join(hash_ids) + ")" )
            hashes = cur.fetchall()

        cur.close()
        return hashes

    pass
